<!--
/**
* Copyright (C) 2022-2023 Timber Chain Cloud (TimberCLD). All Rights Reserved.
* 
* @author: luoweijian
* @email: 807301075@qq..com
* @site: https://www.timbercld.com/
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
*  limitations under the License.
*/
-->
<template>
  <el-dialog v-model="options.visible" :title="!formData.id ? t('add') : t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form v-loading="options.loading" :model="formData" :rules="formRules" ref="formRef" @keyup.enter="submitDataFormHandle()" label-width="120px">
      <el-form-item prop="username" :label="t('user.username')">
        <el-input v-model="formData.username" :placeholder="t('user.username')"></el-input>
      </el-form-item>
      <el-form-item prop="deptName" :label="t('user.deptName')">
        <tcc-dept-tree v-model="formData.deptId" :placeholder="t('dept.title')" :dept-name.sync="formData.deptName" @confirm="getTreeSelect($event)"></tcc-dept-tree>
      </el-form-item>
      <el-form-item prop="password" :label="t('user.password')" :class="{ 'is-required': !formData.id }">
        <el-input v-model="formData.password" type="password" show-password :placeholder="t('user.password')"></el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword" :label="t('user.confirmPassword')" :class="{ 'is-required': !formData.id }">
        <el-input v-model="formData.confirmPassword" type="password" show-password :placeholder="t('user.confirmPassword')"></el-input>
      </el-form-item>
      <el-form-item prop="realName" :label="t('user.realName')">
        <el-input v-model="formData.realName" :placeholder="t('user.realName')"></el-input>
      </el-form-item>
      <el-form-item prop="gender" :label="t('user.gender')">
        <el-radio-group v-model="formData.gender">
          <el-radio :label="item.value" v-for="(item, i) in genderList" :key="i">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="email" :label="t('user.email')">
        <el-input v-model="formData.email" :placeholder="t('user.email')"></el-input>
      </el-form-item>
      <el-form-item prop="mobile" :label="t('user.mobile')">
        <el-input v-model="formData.mobile" :placeholder="t('user.mobile')"></el-input>
      </el-form-item>
      <el-form-item prop="roleIdList" :label="t('user.roleIdList')" class="role-list">
        <el-select v-model="formData.roleIdList" multiple :placeholder="t('user.roleIdList')">
          <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="status" :label="t('user.status')" size="small">
        <el-radio-group v-model="formData.status">
          <el-radio :label="0">{{ t('user.status0') }}</el-radio>
          <el-radio :label="1">{{ t('user.status1') }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="options.visible = false">{{ t('cancel') }}</el-button>
      <el-button type="primary" @click="submitDataFormHandle()">{{ t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { ResType } from '@/utils/request';
import { ElMessage, FormRules } from 'element-plus';
import debounce from 'lodash/debounce';
import type { ElForm } from 'element-plus';
import { isEmail, isMobile } from '@/utils/validate';
import { ref, reactive, nextTick, watch } from 'vue';
import { systemApi } from '@/api/system';
import tccDeptTree from '@/components/tcc-dept-tree/src/tcc-dept-tree.vue';
import type { TreeValue } from '@/components/tcc-dept-tree/src/tcc-dept-tree.vue';
// #region 类型
type RoleValue = {
  id: string;
  name: string;
};
type FormData = {
  id: string;
  username: string;
  deptId: string;
  deptName: string;
  password: string;
  confirmPassword: string;
  realName: string;
  gender: number;
  email: string;
  mobile: string;
  roleIdList: RoleValue[];
  status: number;
};
// #endregion

// #region 属性
const emit = defineEmits<{
  refreshPageHandle: [];
}>();

const { t } = useI18n();
const dialogId = ref('0');
const genderList = ref([
  {
    value: 0,
    label: '男',
  },
  {
    value: 1,
    label: '女',
  },
  {
    value: 2,
    label: '保密',
  },
]);
// 角色列表
const roleList = ref<RoleValue[]>([]);
const formRef = ref<InstanceType<typeof ElForm> | null>(null);
// 表单数据
const formData = reactive<FormData>({
  id: '',
  username: '',
  deptId: '',
  deptName: '',
  password: '',
  confirmPassword: '',
  realName: '',
  gender: 0,
  email: '',
  mobile: '',
  roleIdList: [],
  status: 1,
});
// 页面配置
const options = reactive({
  loading: false,
  visible: false,
});

// #region 自定义验证规则
const validatePassword = (rule: any, value: any, callback: any) => {
  if (!formData.id && !/\S/.test(value)) {
    return callback(new Error(t('validate.required')));
  }
  callback();
};
const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (!formData.id && !/\S/.test(value)) {
    return callback(new Error(t('validate.required')));
  }
  if (formData.password !== value) {
    return callback(new Error(t('user.validate.confirmPassword')));
  }
  callback();
};
const validateEmail = (rule: any, value: any, callback: any) => {
  if (value && !isEmail(value)) {
    return callback(new Error(t('validate.format', { attr: t('user.email') })));
  }
  callback();
};
const validateMobile = (rule: any, value: any, callback: any) => {
  if (value && !isMobile(value)) {
    return callback(new Error(t('validate.format', { attr: t('user.mobile') })));
  }
  callback();
};
// #endregion
const formRules = reactive<FormRules<FormData>>({
  username: [{ required: true, message: t('validate.required'), trigger: 'blur' }],
  deptName: [{ required: true, message: t('validate.required'), trigger: 'change' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
  confirmPassword: [{ validator: validateConfirmPassword, trigger: 'blur' }],
  realName: [{ required: true, message: t('validate.required'), trigger: 'blur' }],
  email: [{ required: true, validator: validateEmail, trigger: 'blur' }],
  mobile: [{ required: true, validator: validateMobile, trigger: 'blur' }],
});
// #endregion

// #region 方法
watch([() => dialogId.value], (val1) => {
  formData.id = val1[0];
});

// 获取角色列表
const getRoleList = async () => {
  systemApi.getRoleList().then((res) => {
    if (res?.code !== 0) {
      ElMessage.error(res.msg);
    } else {
      Object.assign(roleList.value, res.data);
    }
  });
};

// 获取用户信息
const getUserInfo = async () => {
  systemApi.getUserInfo(formData.id).then(async (res) => {
    options.loading = false;
    if (res?.code === 0) {
      await nextTick();
      Object.assign(formData, res.data);
      // 角色配置, 区分是否为默认角色
      // for (let i = 0; i < res.data.roleIdList.length; i++) {
      //   if (options.roleList.filter((item) => item.id === res.data.roleIdList[i])[0]) {
      //     formData.roleIdList.push(res.data.roleIdList[i])
      //     continue
      //   }
      // }
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const init = async () => {
  options.visible = true;
  options.loading = true;
  formData.deptId = '';
  await nextTick();
  formRef.value?.resetFields();
  await Promise.all([getRoleList()]).then(() => {
    if (formData.id) {
      getUserInfo();
    }
  });
  setTimeout(() => {
    options.loading = false;
  }, 500);
};

const getTreeSelect = (e: TreeValue) => {
  formData.deptId = e.id;
  formData.deptName = e.name;
};

// 新增用户
function insertUser() {
  return new Promise<ResType<unknown>>((resolve, reject) => {
    systemApi
      .insertUser(formData)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => [reject(err)]);
  });
}
// 更新用户
function updateUser() {
  return new Promise<ResType<unknown>>((resolve, reject) => {
    systemApi
      .updateUser(formData)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => [reject(err)]);
  });
}
// 表单提交
function submit() {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      options.loading = true;
      let res;
      if (formData.id) {
        res = await updateUser();
      } else {
        res = await insertUser();
        console.log('res-->', res);
      }
      if (res.code === 0) {
        ElMessage.success(t('prompt.success'));
        options.visible = false;
        emit('refreshPageHandle');
      } else {
        ElMessage.error(res.msg);
        options.loading = false;
      }
    }
  });
}
// 防抖
const submitDataFormHandle = debounce(submit, 1000, { leading: true, trailing: false });

defineExpose({
  init,
  dialogId,
});
// #endregion
</script>

<style lang="scss">
.system__user {
  .dept-list {
    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }
  .role-list {
    .el-select {
      width: 100%;
    }
  }
}
</style>
